package eSignDemo

import (
	"context"
	"fmt"
	"github.com/renxingcode/esign-go-sdk"
	eSignTypes "github.com/renxingcode/esign-go-sdk/types"
	"github.com/renxingcode/esign-go-sdk/utils"
	"github.com/zeromicro/go-zero/core/logx"
	"gozero-demo/internal/svc"
	"gozero-demo/internal/types"
)

type CreateFlowOneStepLogic struct {
	logx.Logger
	ctx      context.Context
	svcCtx   *svc.ServiceContext
	eSignSdk *esign.Client
}

// 发起签署流程
func NewCreateFlowOneStepLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateFlowOneStepLogic {
	return &CreateFlowOneStepLogic{
		Logger:   logx.WithContext(ctx),
		ctx:      ctx,
		svcCtx:   svcCtx,
		eSignSdk: svcCtx.ESignSdk,
	}
}

func (l *CreateFlowOneStepLogic) CreateFlowOneStep(req *types.CreateFlowOneStepRequest) (resp *types.CommonResponse, err error) {
	//合同文件列表,通过 /eSignDemo/CreateByTemplate 获取到返回的 templateId 和 fileId, 可能是多个,需要组装成数组形式
	contractFiles := make([]eSignTypes.ESignCreateFlowFiles, 0)
	for _, contractFile := range req.ContractFiles {
		contractFiles = append(contractFiles, eSignTypes.ESignCreateFlowFiles{
			TemplateId: contractFile.TemplateId,
			EFileId:    contractFile.EFileId,
		})
	}

	//设置请求参数
	requestESignCreateFlowData := &eSignTypes.ESignCreateFlowRequestData{
		SignerName:    req.SignerName,
		SignerPhone:   req.SignerPhone,
		CompanySealID: "", //可以留空,将会使用默认的公司印章
		ContractFiles: contractFiles,
	}
	createFlowResponse, err := l.eSignSdk.Sign.ESignCreateFlowOneStep(requestESignCreateFlowData, true)
	if err != nil {
		return nil, err
	}

	createFlowResponseData := eSignTypes.ESignCreateFlowResponseData{}
	err = utils.JsonUnmarshalToStruct(createFlowResponse.Data, &createFlowResponseData)
	if err != nil {
		return nil, err
	}

	//这里获取到的flowId需要保存起来,可以用来:1.查询签署链接; 2.撤回签署流程; 3.签署完成后查询合同文档;
	fmt.Printf("createFlowResponseData flowId: %v", createFlowResponseData.ESignFlowId)

	return types.SuccessResponse(createFlowResponseData, l.ctx), nil
}
